<template>
  <div class="bom-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h2>BOM管理</h2>
        <p class="page-description">管理产品物料清单，支持多层级BOM结构和版本控制</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showAddDialog" :icon="Plus">
          新增BOM
        </el-button>
        <el-button @click="exportBom" :icon="Download">
          导出BOM
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入产品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="BOM编号">
          <el-input
            v-model="searchForm.bomCode"
            placeholder="请输入BOM编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="草稿" value="draft" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本">
          <el-input
            v-model="searchForm.version"
            placeholder="请输入版本号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="resetSearch" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- BOM列表 -->
    <div class="table-section">
      <el-table
        :data="bomList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="bomCode" label="BOM编号" width="150" />
        <el-table-column prop="productName" label="产品名称" width="200" />
        <el-table-column prop="productCode" label="产品编号" width="150" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="totalCost" label="总成本" width="120">
          <template #default="scope">
            <span class="cost-text">¥{{ scope.row.totalCost.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="materialCount" label="物料数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'active' ? 'success' : scope.row.status === 'inactive' ? 'danger' : 'warning'"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewBomDetail(scope.row)" :icon="View">
              查看
            </el-button>
            <el-button size="small" type="primary" @click="editBom(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" @click="copyBom(scope.row)" :icon="CopyDocument">
              复制
            </el-button>
            <el-button size="small" type="danger" @click="deleteBom(scope.row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑BOM对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="bomFormRef"
        :model="bomForm"
        :rules="bomRules"
        label-width="120px"
        class="bom-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="BOM编号" prop="bomCode">
              <el-input v-model="bomForm.bomCode" placeholder="请输入BOM编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="bomForm.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="bomForm.productCode" placeholder="请输入产品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="bomForm.version" placeholder="请输入版本号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="bomForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
                <el-option label="草稿" value="draft" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产数量" prop="quantity">
              <el-input-number
                v-model="bomForm.quantity"
                :min="1"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="bomForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <!-- BOM物料清单 -->
        <el-form-item label="物料清单">
          <div class="material-list-section">
            <div class="material-list-header">
              <span>物料清单</span>
              <el-button size="small" type="primary" @click="addMaterial" :icon="Plus">
                添加物料
              </el-button>
            </div>
            <el-table :data="bomForm.materials" border style="width: 100%">
              <el-table-column prop="materialCode" label="物料编号" width="150" />
              <el-table-column prop="materialName" label="物料名称" width="200" />
              <el-table-column prop="specification" label="规格型号" width="150" />
              <el-table-column prop="unit" label="单位" width="80" />
              <el-table-column prop="quantity" label="用量" width="100">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.quantity"
                    :min="0"
                    :precision="2"
                    size="small"
                    @change="calculateCost"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价" width="100">
                <template #default="scope">
                  <span>¥{{ scope.row.unitPrice.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalPrice" label="小计" width="100">
                <template #default="scope">
                  <span>¥{{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="removeMaterial(scope.$index)"
                    :icon="Delete"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="cost-summary">
              <span>总成本：¥{{ totalCost.toFixed(2) }}</span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveBom" :loading="saving">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- BOM详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="BOM详情" width="70%">
      <div class="bom-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="BOM编号">{{ currentBom.bomCode }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ currentBom.productName }}</el-descriptions-item>
          <el-descriptions-item label="产品编号">{{ currentBom.productCode }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ currentBom.version }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentBom.status === 'active' ? 'success' : currentBom.status === 'inactive' ? 'danger' : 'warning'">
              {{ getStatusText(currentBom.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总成本">¥{{ currentBom.totalCost?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentBom.createTime }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentBom.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin: 20px 0 10px 0">物料清单</h3>
        <el-table :data="currentBom.materials" border style="width: 100%">
          <el-table-column prop="materialCode" label="物料编号" width="150" />
          <el-table-column prop="materialName" label="物料名称" width="200" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="quantity" label="用量" width="100" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="scope">
              <span>¥{{ scope.row.unitPrice.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="小计" width="100">
            <template #default="scope">
              <span>¥{{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 添加物料对话框 -->
    <el-dialog v-model="materialDialogVisible" title="选择物料" width="60%">
      <el-table
        :data="availableMaterials"
        @selection-change="handleMaterialSelection"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="物料编号" width="150" />
        <el-table-column prop="materialName" label="物料名称" width="200" />
        <el-table-column prop="specification" label="规格型号" width="150" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            <span>¥{{ scope.row.unitPrice.toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddMaterial">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Download,
  Search,
  Refresh,
  View,
  Edit,
  Delete,
  CopyDocument
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const materialDialogVisible = ref(false)
const bomFormRef = ref()

// 搜索表单
const searchForm = reactive({
  productName: '',
  bomCode: '',
  status: '',
  version: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// BOM列表
const bomList = ref([])
const selectedBoms = ref([])
const currentBom = ref({})

// BOM表单
const bomForm = reactive({
  id: null,
  bomCode: '',
  productName: '',
  productCode: '',
  version: '',
  status: 'draft',
  quantity: 1,
  remark: '',
  materials: []
})

// 表单验证规则
const bomRules = {
  bomCode: [
    { required: true, message: '请输入BOM编号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  productCode: [
    { required: true, message: '请输入产品编号', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 可选物料列表
const availableMaterials = ref([])
const selectedMaterials = ref([])

// 计算属性
const dialogTitle = computed(() => {
  return bomForm.id ? '编辑BOM' : '新增BOM'
})

const totalCost = computed(() => {
  return bomForm.materials.reduce((total, material) => {
    return total + (material.quantity * material.unitPrice)
  }, 0)
})

// 方法
const getStatusText = (status) => {
  const statusMap = {
    active: '启用',
    inactive: '禁用',
    draft: '草稿'
  }
  return statusMap[status] || status
}

const loadBomList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        bomCode: 'BOM001',
        productName: '智能手机X1',
        productCode: 'PHONE001',
        version: 'V1.0',
        status: 'active',
        totalCost: 1250.50,
        materialCount: 15,
        createTime: '2024-01-15 10:30:00',
        remark: '主力产品BOM',
        materials: [
          {
            materialCode: 'MAT001',
            materialName: '处理器芯片',
            specification: 'A15',
            unit: '个',
            quantity: 1,
            unitPrice: 500.00
          },
          {
            materialCode: 'MAT002',
            materialName: '内存条',
            specification: '8GB',
            unit: '个',
            quantity: 1,
            unitPrice: 200.00
          },
          {
            materialCode: 'MAT003',
            materialName: '屏幕',
            specification: '6.1寸OLED',
            unit: '个',
            quantity: 1,
            unitPrice: 300.00
          }
        ]
      },
      {
        id: 2,
        bomCode: 'BOM002',
        productName: '平板电脑T1',
        productCode: 'TABLET001',
        version: 'V2.1',
        status: 'active',
        totalCost: 890.30,
        materialCount: 12,
        createTime: '2024-01-20 14:20:00',
        remark: '平板产品BOM',
        materials: [
          {
            materialCode: 'MAT004',
            materialName: '平板处理器',
            specification: 'M1',
            unit: '个',
            quantity: 1,
            unitPrice: 400.00
          },
          {
            materialCode: 'MAT005',
            materialName: '平板屏幕',
            specification: '10.9寸LCD',
            unit: '个',
            quantity: 1,
            unitPrice: 250.00
          }
        ]
      },
      {
        id: 3,
        bomCode: 'BOM003',
        productName: '智能手表W1',
        productCode: 'WATCH001',
        version: 'V1.5',
        status: 'draft',
        totalCost: 320.80,
        materialCount: 8,
        createTime: '2024-01-25 09:15:00',
        remark: '新产品BOM开发中',
        materials: [
          {
            materialCode: 'MAT006',
            materialName: '手表芯片',
            specification: 'S7',
            unit: '个',
            quantity: 1,
            unitPrice: 150.00
          },
          {
            materialCode: 'MAT007',
            materialName: '手表屏幕',
            specification: '1.9寸AMOLED',
            unit: '个',
            quantity: 1,
            unitPrice: 120.00
          }
        ]
      }
    ]
    
    bomList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('加载BOM列表失败')
  } finally {
    loading.value = false
  }
}

const loadAvailableMaterials = async () => {
  // 模拟可选物料数据
  availableMaterials.value = [
    {
      materialCode: 'MAT001',
      materialName: '处理器芯片',
      specification: 'A15',
      unit: '个',
      unitPrice: 500.00
    },
    {
      materialCode: 'MAT002',
      materialName: '内存条',
      specification: '8GB',
      unit: '个',
      unitPrice: 200.00
    },
    {
      materialCode: 'MAT003',
      materialName: '屏幕',
      specification: '6.1寸OLED',
      unit: '个',
      unitPrice: 300.00
    },
    {
      materialCode: 'MAT008',
      materialName: '电池',
      specification: '3000mAh',
      unit: '个',
      unitPrice: 80.00
    },
    {
      materialCode: 'MAT009',
      materialName: '摄像头',
      specification: '48MP',
      unit: '个',
      unitPrice: 150.00
    }
  ]
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadBomList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    productName: '',
    bomCode: '',
    status: '',
    version: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedBoms.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadBomList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadBomList()
}

const showAddDialog = () => {
  resetBomForm()
  dialogVisible.value = true
}

const resetBomForm = () => {
  Object.assign(bomForm, {
    id: null,
    bomCode: '',
    productName: '',
    productCode: '',
    version: '',
    status: 'draft',
    quantity: 1,
    remark: '',
    materials: []
  })
  bomFormRef.value?.clearValidate()
}

const editBom = (row) => {
  Object.assign(bomForm, {
    ...row,
    materials: [...row.materials]
  })
  dialogVisible.value = true
}

const viewBomDetail = (row) => {
  currentBom.value = row
  detailDialogVisible.value = true
}

const copyBom = (row) => {
  Object.assign(bomForm, {
    ...row,
    id: null,
    bomCode: '',
    version: '',
    materials: [...row.materials]
  })
  dialogVisible.value = true
}

const deleteBom = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除BOM "${row.bomCode}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    ElMessage.success('删除成功')
    loadBomList()
  } catch {
    // 用户取消删除
  }
}

const saveBom = async () => {
  try {
    await bomFormRef.value.validate()
    
    saving.value = true
    
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(bomForm.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    loadBomList()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

const handleDialogClose = () => {
  bomFormRef.value?.clearValidate()
}

const addMaterial = () => {
  materialDialogVisible.value = true
}

const handleMaterialSelection = (selection) => {
  selectedMaterials.value = selection
}

const confirmAddMaterial = () => {
  selectedMaterials.value.forEach(material => {
    const existingMaterial = bomForm.materials.find(m => m.materialCode === material.materialCode)
    if (!existingMaterial) {
      bomForm.materials.push({
        ...material,
        quantity: 1
      })
    }
  })
  materialDialogVisible.value = false
  selectedMaterials.value = []
  calculateCost()
}

const removeMaterial = (index) => {
  bomForm.materials.splice(index, 1)
  calculateCost()
}

const calculateCost = () => {
  // 触发计算属性更新
}

const exportBom = () => {
  ElMessage.success('导出功能开发中')
}

// 生命周期
onMounted(() => {
  loadBomList()
  loadAvailableMaterials()
})
</script>

<style scoped>
.bom-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.cost-text {
  color: #e6a23c;
  font-weight: bold;
}

.bom-form {
  max-height: 60vh;
  overflow-y: auto;
}

.material-list-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.material-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.cost-summary {
  margin-top: 10px;
  text-align: right;
  font-size: 16px;
  font-weight: bold;
  color: #e6a23c;
}

.bom-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bom-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
}
</style>